package com.lifeng.controller;

import com.lifeng.domain.UserBean;
import com.lifeng.mapper.UserMapper;
import com.lifeng.test.MySpringUtil;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;


/**
 * Created by lifeng on 2019/4/30.
 */
@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/sql")
    @ResponseBody
    public Object sql(String table){
        StringBuilder sb = new StringBuilder();
        List<UserBean> list = userMapper.selectAll();
        for(UserBean userBean : list){
            String pwd = userBean.getPassword();
            pwd = encode(pwd);
            String sqlline = "update " + table + " set password='" + pwd + "' where id="+ userBean.getId()+";";
            //String sqlline = "update " + table + " set user_password='" + pwd + "' where user_id='"+ userBean.getId()+"';";
            log.info(sqlline);
            sb.append(sqlline);
            sb.append("<br/>");
        }
        return sb.toString();
    }

    public String encode(String password) {
        try {
            System.out.println("先对密码做sha256加密");
            byte[] sha256 = MessageDigest.getInstance("SHA-256").digest(StringUtils.getBytesUtf8(password));
            String sha256Hex = Hex.encodeHexString(sha256);
            System.out.println("最后密码密文:"+sha256Hex);
            return sha256Hex;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("密码加密异常");
        }
        return null;
    }
}
